public class SafeTransferWithSynchronized {
    static class Account {
        private String name;
        private int balance;
        private static final Object lock = new Object();

        public Account(String name, int balance) {
            this.name = name;
            this.balance = balance;
        }

        public void transfer(Account to, int amount) {
            // 确定锁的顺序，避免死锁
            Account first = this.name.compareTo(to.name) < 0 ? this : to;
            Account second = this.name.compareTo(to.name) < 0 ? to : this;

            synchronized (first) {
                System.out.println(Thread.currentThread().getName() + " 持有锁: " + first.name);

                synchronized (second) {
                    System.out.println(Thread.currentThread().getName() + " 持有锁: " + second.name);

                    if (this.balance >= amount) {
                        this.balance -= amount;
                        to.balance += amount;
                        System.out.println("转账成功: " + amount + " 从 " + this.name + " 到 " + to.name);
                    } else {
                        System.out.println("余额不足，转账失败");
                    }
                }
            }
        }
    }

    public static void main(String[] args) {
        Account accountA = new Account("商家A", 1000);
        Account accountB = new Account("客户B", 1000);

        // 线程1: A向B转账200
        Thread thread1 = new Thread(() -> accountA.transfer(accountB, 200), "Thread-1");

        // 线程2: B向A转账300
        Thread thread2 = new Thread(() -> accountB.transfer(accountA, 300), "Thread-2");

        thread1.start();
        thread2.start();

        try {
            thread1.join();
            thread2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("商家A余额: " + accountA.balance);
        System.out.println("客户B余额: " + accountB.balance);
    }
}